import { Panel, LayerLink, ImgHolder } from 'comps/common';
import UserRole from '../containers/user-role';
import { Form, Input, Button, Table, Modal, Icon, Popconfirm } from 'antd';
import * as React from 'react';
import UserInfo from '../../profile/containers/user-info';
import UserAddModal from './user-add';
import UserResetPasswordModal from './user-reset-password';

const FormItem = Form.Item;

class UserSearchForm extends React.Component {

  checkQuery(rule, value, callback) {
    if (!value || /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*|^\d*$/.test(value)) {
      callback();
    } else {
      callback('请输入用户邮箱或 ID 进行检索')
    }
  }

  onSubmit(evt) {
    evt.preventDefault();
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (!!errors) {
        return;
      }
      this.props.onSearchSubmit(values);
    });

  }

  render() {
    const queryProps = this.props.form.getFieldProps('key', {
      rules: [
        { validator: this.checkQuery.bind(this) }
      ]
    });
    return (
      <Form inline form={this.props.form} className='search-form' onSubmit={::this.onSubmit}>
        <FormItem label='用户邮箱/ID：'>
          <Input style={{ width: '300px' }} placeholder='可输入用户邮箱或 ID 进行检索' {...queryProps}/>
        </FormItem>
        <Button htmlType='submit' type='primary'><Icon type='search'/>搜索</Button>
      </Form>
    );
  }
}
UserSearchForm = Form.create()(UserSearchForm);

class UserManageList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1
    };
  }

  submitSearch() {
    const { searchForm } = this.refs
    return this.props.onSearchSubmit(searchForm.getFieldsValue());
  }

  addUser() {
    this.refs.userAddModal.showModal()
  }

  resetPassword(user) {
    return ()=> {
      return this.refs.userResetPasswordModal.showModal(user)
    }
  }

  createUser(user) {
    return this.props.onCreateUser(user)
      .then(()=>this.submitSearch())
  }

  lockUser(user) {
    return ()=> {
      this.props.lockUser(user)
        .then(()=>this.submitSearch())
    }
  }

  unlockUser(user) {
    return () => {
      this.props.unlockUser(user)
        .then(() => this.submitSearch());
    };
  }

  getOperator(t, record) { // TODO 这里密码的图标不对
    return {
      NEW: <Button type='primary' onConfirm={::this.resetPassword(record)}><Icon type='eye-o'/>重置密码</Button>,
      ACTIVE: (
        <span>
          <Popconfirm title="确定要锁定这个用户吗？" onConfirm={::this.lockUser(record)}>
            <Button className="btn" type='primary'><Icon type='lock'/>锁定</Button>
          </Popconfirm>
          <Button className="btn" type='ghost' onClick={::this.resetPassword(record)}><Icon type='eye-o'/>重置密码</Button>
          <LayerLink component={UserRole} data={{ user: record }} title={`用户（${record.email}）权限管理`}>
            权限管理
          </LayerLink>
        </span>
      ),
      LOCK: <Popconfirm title="确定要解锁这个用户吗？" onConfirm={::this.unlockUser(record)}>
        <Button type='primary'><Icon type='unlock'/>解锁</Button>
      </Popconfirm>
    }
      [record.status];
  }

  render() {
    const { users = {}, onSearchSubmit } = this.props;
    const { list = [], total } = users;

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id'
      }, {
        title: '昵称',
        dataIndex: 'nick',
        key: 'nick',
        render: (nick, user) => <LayerLink component={UserInfo} data={{ email: user.email }} title={`用户（${nick}）信息`}>
          <span><ImgHolder className='user-logo' src={user.avatar} rect='40x40'
            text={user.email.substring(0, 1)}/>{nick}</span>
        </LayerLink>
      }, {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email'
      }, {
        title: '手机号',
        dataIndex: 'mobile',
        key: 'mobile'
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (status) => {
          return {
            NEW: '未激活',
            ACTIVE: '正常',
            LOCK: '已锁定'
          }[status];
        }
      }, {
        title: '操作',
        key: 'operator',
        render: ::this.getOperator
      }
    ];

    const pagination = {
      total,
      current: this.state.currentPage,
      onChange: (pageNo) => {
        const query = {
          ...this.refs.searchForm.getFieldsValue(),
          pageNo
        };
        this.props.onSearchSubmit(query)
          .then(() => {
            this.setState({ currentPage: pageNo });
          });
      }
    };

    return (
      <Panel>
        <UserSearchForm ref='searchForm' onSearchSubmit={onSearchSubmit}/>
        <Button type='primary' style={{ marginBottom: '20px' }} onClick={::this.addUser}><Icon type='users'/>
          新建用户</Button>
        <Table className="user-manage-list" dataSource={list} columns={columns} pagination={pagination}
          rowKey={it => it.id}/>
        <UserAddModal ref="userAddModal" onSave={::this.createUser}/>
        <UserResetPasswordModal ref="userResetPasswordModal" onResetPassword={::this.props.resetPassword}/>
      </Panel>
    );
  }
}

export default UserManageList;
